<template>
  <el-form 
    ref="formRef" 
    :model="form" 
    :rules="rules" 
    label-width="80px" 
    class="demo-ruleForm"
  >
    <el-form-item label="用户名" prop="userName">
      <el-input v-model="form.userName"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="passWord">
      <el-input 
        type="password" 
        v-model="form.passWord" 
        autocomplete="off"
      ></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleSubmit">登录</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
    <el-form-item>
      <el-link type="primary" @click="toggleMode('register')">去注册</el-link>
      <el-link type="primary" @click="toggleMode('forgetPassword')" style="margin-left: 10px;">忘记密码？</el-link>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { ElMessage,ElNotification } from 'element-plus';
import { useRouter,useRoute } from 'vue-router'

import { defineEmits } from 'vue';
// 1.2 import store
import useUserStore from '@/store/modules/user'

const emit = defineEmits(['toggle-mode']);

// 2.1.2 define router
const $router = useRouter();
// 3.1 路由对象  用户接收query参数处理
const $route = useRoute();

const userStore = useUserStore();

const formRef = ref(null);

const form = reactive({
  userName: '',
  passWord: ''
});

const rules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  passWord: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
  ]
};

const  handleSubmit =  () => {
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (valid) {
    
      // 模拟登录逻辑
      userStore.userLogin(form).then((res) => {
          console.log(res)
          // 1 if success, jump to home
          jumpPointPage();
          ElNotification({
            type: 'success',
            message: '登录成功',
            title: `欢迎使用知识库系统,,${form.userName}`,
          })
        })
        .catch((err) => {
          // 2 if fail, show error msg
          const error = err || { message: '登录失败，用户名密码不正确' };
          console.log(error);
          ElNotification({
            type: 'error',
            message: error || '登录失败，请重试。',
          });
        })
    } else {
      console.log('error submit!');
      return false;
    }
  });
};

// 3.1 jump page
const jumpPointPage = () =>{
  // 如果有queyy
  let redirectPath = $route.query.redirect;
  // 跳转
  $router.push({ path: redirectPath || '/home' })
}


const resetForm = () => {
  if (!formRef.value) return;
  formRef.value.resetFields();
};

const toggleMode = (mode) => {
  emit('toggle-mode', mode);
};
</script>